package org.kth.dks.dks_comm;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

//This class implements primitives for sending and receiving
//data.

class ConnMessageMiscs{
	static private Logger log = Logger.getLogger(ConnMessageMiscs.class);
	static private final int MAXBUFFERSIZE            = 1024*1024*128;
	
	static public byte [] m_readDataBlock(DataInputStream in ) throws IOException {
		int size = in.readInt();
		if( size <= 0 || size > MAXBUFFERSIZE ) {
			log.error( "MAXBUFFERSIZE="+MAXBUFFERSIZE+" received:"+size);
			// Here we should throw some exception.
			return null;
		}
		byte buffer[] = new byte[size];
		in.readFully( buffer );
		return buffer;
	}
	
	static public void m_writeDataBlock(byte [] buffer, DataOutputStream out) throws IOException {
		int size = buffer.length;
		if( size <= 0 || size > MAXBUFFERSIZE ) {
			log.error( "MAXBUFFERSIZE="+MAXBUFFERSIZE+" received:"+size);
			return;
		}
		// Here we should throw some exception.
		log.debug("Sending msg of size:"+size);
		out.writeInt( size );
		out.write( buffer );
	}
	
}
